import Vue from "vue";
import { message, notification } from "ant-design-vue";

var webSocket = null;
// 连接状态
var isConnect = false;
// 定义外部接收数据的回调函数
// var globalCallback = function (e) { console.log(e) }
var globalCallback = function (e) {};
// 重连次数
var reConnectNum = 0;

// var websocketUrl = "ws://10.10.7.51:31736/coffee-proj/websocket/admin";
// var websocketUrl = "ws://172.28.18.240:36002/coffee-proj/websocket/admin";
var websocketUrl = "ws://10.10.10.53:30156/coffee-proj/websocket/admin";


//心跳设置
var heartCheck = {
  // 心跳包
  heartbeatData: {
    testHeart: {
      value: 1,
    },
  },
  // 每段时间发送一次心跳包 这里设置为60s
  timeout: 25 * 1000,
  // 延时发送消息对象(启动心跳新建这个对象，收到消息后重置对象)
  heartbeat: null,
  start: function () {
    this.heartbeat = setInterval(() => {
      if (isConnect) {
        webSocketSend(this.heartbeatData);
      } else {
        this.clear();
      }
    }, this.timeout);
  },
  reset: function () {
    clearInterval(this.heartbeat);
    this.start();
  },
  clear: function () {
    clearInterval(this.heartbeat);
  },
};

//初始化websocket
function initWebSocket(callback) {
  //此callback为在其他地方调用时定义的接收socket数据的函数
  if (callback) {
    if (typeof callback == "function") {
      globalCallback = callback;
    } else {
      throw new Error("callback is not a function");
    }
  }
  if ("WebSocket" in window) {
    webSocket = new WebSocket(websocketUrl);
  } else {
    notification.open({
      type:"error",
      message: "Error",
      description: "该浏览器不支持websocket!",
      style:{backgroundColor:'#fff1f0',border:'2px solid #ffa39e',borderRadius:'8px'},
      onClick: () => {
      },
    });
    // message.error("该浏览器不支持websocket!");
    return;
  }
  //打开
  webSocket.onopen = function () {
    webSocketOpen();
  };
  //收信
  webSocket.onmessage = function (e) {
    webSocketOnMessage(e);
  };
  //关闭
  webSocket.onclose = function (e) {
    webSocketOnClose(e);
  };
  //连接发生错误的回调方法
  webSocket.onerror = function (e) {
    webSocketonError(e);
  };
}

//连接socket建立时触发
function webSocketOpen() {
  console.log("WebSocket连接成功");
  //首次握手
  // webSocketSend(heartCheck.heartbeatData)
  isConnect = true;
  heartCheck.start();
  reConnectNum = 0;
}

//客户端接收服务端数据时触发,e为接受的数据对象
function webSocketOnMessage(e) {
  // console.log("websocket信息:")
  // console.log(e.data)
  const data = JSON.parse(e.data);
  // console.log(data)
  globalCallback(data);
}

//socket关闭时触发
function webSocketOnClose(e) {
  console.log("关闭了");
  heartCheck.clear();
  isConnect = false; //断开后修改标识
  // console.log(e)
  // console.log('webSocket已经关闭 (code：' + e.code + ')')
  //被动断开，重新连接
  // console.log(e);
  if (e.code == 1006) {
    if (reConnectNum < 10) {
      initWebSocket();
      ++reConnectNum;
      notification.open({
        type:"error",
        message: "Error",
        description: '正在尝试重新连接第'+reConnectNum+'次',
        style:{borderRadius:'8px'},
        // getContainer: () => this.$refs.layoutContent,
        onClick: () => {
          // console.log("Notification Clicked!");
        },
      });
    } else {
      notification.open({
        type:"error",
        message: "Error",
        description: "websocket连接不上,请刷新页面或联系开发人员",
        duration: 0,
        btn: (h) => {
          return h(
            "a-button",
            {
              props: {
                type: "",
                size: "",
              },
              on: {
                click: () => {window.location.reload()},
              },
            },
            "刷新"
          );
        },
        style:{borderRadius:'8px'},
        // getContainer: () => this.$refs.layoutContent,
        onClick: () => {
          // console.log("Notification Clicked!");
        },
      });
      // message.error("websocket连接不上，请刷新页面或联系开发人员!");
    }
  }
}

//连接发生错误的回调方法
function webSocketonError(e) {
  console.log("异常了");
  heartCheck.clear();
  isConnect = false; //断开后修改标识
  console.log("WebSocket连接发生错误:");
  // notification.open({
  //   type:"error",
  //   message: "Error",
  //   description: "WebSocket连接发生错误:"+e.errMessage,
  //   style:{borderRadius:'8px'},
  //   onClick: () => {
  //   },
  // });
  console.log(e);
}

//发送数据
function webSocketSend(data) {
  webSocket.send(data);
}
//在其他需要socket地方主动关闭socket
function closeWebSocket(e) {
  console.log("主动-关闭了");
  webSocket.close();
  heartCheck.clear();
  isConnect = false;
  reConnectNum = 0;
}
//在其他需要socket地方接受数据
function getSock(callback) {
  globalCallback = callback;
}
//在其他需要socket地方调用的函数，用来发送数据及接受数据
function sendSock(agentData) {
  //下面的判断主要是考虑到socket连接可能中断或者其他的因素，可以重新发送此条消息。
  switch (webSocket.readyState) {
    //CONNECTING：值为0，表示正在连接。
    case webSocket.CONNECTING:
      setTimeout(function () {
        sendSock(agentData, callback);
      }, 1000);
      break;
    //OPEN：值为1，表示连接成功，可以通信了。
    case webSocket.OPEN:
      webSocketSend(agentData);
      break;
    //CLOSING：值为2，表示连接正在关闭。
    case webSocket.CLOSING:
      setTimeout(function () {
        sendSock(agentData, callback);
      }, 1000);
      break;
    //CLOSED：值为3，表示连接已经关闭，或者打开连接失败。
    case webSocket.CLOSED:
      // do something
      break;
    default:
      // this never happens
      break;
  }
}

export default {
  init: initWebSocket,
  close: closeWebSocket,
  send: sendSock,
  get: getSock,
};
